<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\AuthRole;
use App\Models\AuthRoleMenu;
use Illuminate\Http\Request;

class AuthRoleController extends Controller
{
    public function index(Request $request)
    {
        $model = AuthRole::query();
        $model = $model->orderBy('created_at', 'desc');
        $result = $model->get();
        foreach ($result as $value) {
            $value['role_ids'] = explode(',', $value['role_ids']);
        }
        return showMsg('获取成功！', 200, $result);
    }

    public function detail(Request $request)
    {
        $id = $request->get('id');
        $result = AuthRole::where('role_id', $id)->first();
        if (!$result) {
            return showMsg('信息已删除', 201, $result);
        }
        $result['role_ids'] = explode(',', $result['role_ids']);
        return showMsg('操作成功', 200, $result);
    }

    public function beforeSave(Request $request)
    {
        $id = $request->get('role_id');
        $data = $request->all();
        $json['role_name'] = $data['role_name'];
        $json['memo'] = $data['memo'];
        if ($data['ids']) {
            $json['role_ids'] = implode(',', $data['ids']);
        }
        if ($id) {
            $article = AuthRole::findOrFail($id);
            if ($article->update($json)) {
                return showMsg('更新成功', 200);
            }
        } else {
            AuthRole::create($json);
            return showMsg('添加成功', 200);
        }
    }

    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return showMsg('请选择操作项', 201);
        }
        if (is_array($ids)) {
            foreach ($ids as $v) {
                AuthRole::where('role_id', $ids)->delete();
            }
        } else {
            AuthRole::where('role_id', $ids)->delete();
            AuthRoleMenu::where('role_id', $ids);
        }
        return showMsg('删除成功', 200);
    }

    public function setAuthRole(Request $request)
    {
        $role_id = $request->get('role_id');
        $ids = $request->get('ids');
        $role_ids = implode(',', $ids);
        AuthRole::where('role_id', $role_id)->update(['role_ids' => $role_ids]);
        AuthRoleMenu::where('role_id', $role_id)->delete();
        foreach ($ids as $val) {
            $json['role_id'] = $role_id;
            $json['menu_id'] = $val;
            $json['operate'] = 1;
            AuthRoleMenu::create($json);
        }
        return showMsg('设置成功', 200);
    }

}